//
//  FunctionMethod.m
//  SportSocial
//
//  Created by yull on 14/12/28.
//  Copyright (c) 2014年 yull. All rights reserved.
//

#import "FunctionMethod.h"
#import <CoreLocation/CoreLocation.h>
#import "UserNet.h"

@implementation FunctionMethod
+ (double)distanceBetweenOrderByLat1:(double)lat1 lat2:(double)lat2 lng1:(double)lng1 lng2:(double)lng2
{
    CLLocation* curLocation = [[CLLocation alloc] initWithLatitude:lat1 longitude:lng1];
    CLLocation* otherLocation = [[CLLocation alloc] initWithLatitude:lat2 longitude:lng2];
    double distance  = [curLocation distanceFromLocation:otherLocation];
    return distance;
}

+ (UserModel *)getUserModelWithUserId:(UInt64)userId
{    
    UserModel *userModel = [[UserDao shareInstance] selectUserWithId:userId];
    if (!userModel) {
        NSString *url = [[NSString alloc] initWithFormat:@"http://www.tengzhenkeji.com:9081/api/user/query?token=%@&id=%lld",[CurrentUser shareInstance].token,userId];
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
        
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        
        NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSDictionary *dict = [responseDict objectForKey:@"data"];
        userModel = [UserModel userWithDict:dict];
        
        [[UserDao shareInstance] addOrUpdateUser:userModel];
    }
    return userModel;
}

+ (NSString *)dbDirectoryPath
{
    return [NSString stringWithFormat:@"%@/Documents/db",NSHomeDirectory()];
}

+ (NSString *)picDiretoryPath
{
    return [NSString stringWithFormat:@"%@/Documents/pic",NSHomeDirectory()];
}

+ (NSString *)audioDiretoryPath
{
    return [NSString stringWithFormat:@"%@/Documents/audio",NSHomeDirectory()];
}

+ (NSString*) gen_uuid
{
    CFUUIDRef uuid_ref = CFUUIDCreate(NULL);
    CFStringRef uuid_string_ref= CFUUIDCreateString(NULL, uuid_ref);
    CFRelease(uuid_ref);
    NSString *uuid = [NSString stringWithString:(__bridge NSString*)uuid_string_ref];
    CFRelease(uuid_string_ref);
    
    uuid = [uuid lowercaseString];
    return uuid;
}

+ (NSString *)createPicPath
{
    return [[NSString alloc] initWithFormat:@"%@/%@",[FunctionMethod picDiretoryPath],[FunctionMethod gen_uuid]];
}

+ (NSString *)createAudioPath
{
    return [[NSString alloc] initWithFormat:@"%@/%@",[FunctionMethod audioDiretoryPath],[FunctionMethod gen_uuid]];
}

#pragma mark - 聊天时间
+ (NSString *)getChatTimeTextWithTimeStamp:(NSTimeInterval)timeStamp
{
    timeStamp = timeStamp / 1000;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeStamp];
    NSDate *nowDate = [NSDate date];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    NSTimeInterval nowTimeInterval = [nowDate timeIntervalSince1970];
    if (nowTimeInterval + 24 * 60 * 60 < timeStamp) {
        formatter.dateFormat = @"yyyy年M月d日";
        return [formatter stringFromDate:date];
    }
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
    
    NSDateComponents *nowComponents = [calendar components:unit fromDate:nowDate];
    NSDateComponents *dateComponents = [calendar components:unit fromDate:date];
    
    NSInteger dayDif = [self getDayDiffFromComponents:nowComponents toComponents:dateComponents];
    
    NSString *dateFormat = @"yyyy-MM-dd";
    if (dayDif == 0) {
        dateFormat = @"今天 HH:mm";
    }else if (dayDif == 1) {
        dateFormat = @"昨天 HH:mm";
    }else if (dayDif == 2) {
        dateFormat = @"前天 HH:mm";
    }else if (nowComponents.year == dateComponents.year) {
        dateFormat = @"MM-dd";
    }
    formatter.dateFormat = dateFormat;
    return [formatter stringFromDate:date];
}

+ (NSString *)getRefreshTimeTextWithTimeStamp:(NSTimeInterval)timeStamp
{
    if (timeStamp < 0.1) {
        return @"";
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeStamp];
    NSDate *nowDate = [NSDate date];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    NSTimeInterval nowTimeInterval = [nowDate timeIntervalSince1970];
    if (nowTimeInterval + 24 * 60 * 60 < timeStamp) {
        formatter.dateFormat = @"yyyy年M月d日";
        return [formatter stringFromDate:date];
    }
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
    
    NSDateComponents *nowComponents = [calendar components:unit fromDate:nowDate];
    NSDateComponents *dateComponents = [calendar components:unit fromDate:date];
    
    NSInteger dayDif = [self getDayDiffFromComponents:nowComponents toComponents:dateComponents];
    
    NSString *dateFormat = @"yyyy-MM-dd";
    if (dayDif == 0) {
        dateFormat = @"HH:mm";
    }else if (dayDif == 1) {
        dateFormat = @"昨天 HH:mm";
    }else if (dayDif == 2) {
        dateFormat = @"前天 HH:mm";
    }else if (nowComponents.year == dateComponents.year) {
        dateFormat = @"MM-dd";
    }
    formatter.dateFormat = dateFormat;
    return [formatter stringFromDate:date];
}

+ (NSInteger)getDayDiffFromComponents:(NSDateComponents *)currentComponets toComponents:(NSDateComponents *)components{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSInteger yearDif = currentComponets.year - components.year;
    NSInteger monthDif= currentComponets.month - components.month;
    NSInteger dayDif= currentComponets.day - components.day;
    if (yearDif == 1 && currentComponets.month == 1 && components.month == 12){
        return (currentComponets.day + 31 - components.day);
    }else if (yearDif == 0 && monthDif == 1) {
        NSDate *date = [calendar dateFromComponents:components];
        NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
        NSInteger dif = currentComponets.day + range.length - components.day;
        if (dif <= 2) {
            return dif;
        }
    }else if (yearDif == 0 && monthDif == 0 && dayDif <= 2) {
        return dayDif;
    }
    return -1;
}

+ (BOOL)networkAvailable
{
    Reachability *curReach = [Reachability reachabilityForInternetConnection];
    return [curReach isReachable];
}
@end
